/*
 * Copyright 2017-2020 吴学文 and java110 team.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.java110.mall.chain.cmd.chainProduct;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.file.FileDto;
import com.java110.dto.file.FileRelDto;
import com.java110.intf.chain.IChainProductDetailV1InnerServiceSMO;
import com.java110.intf.chain.IChainProductV1InnerServiceSMO;
import com.java110.intf.chain.IChainProductValueV1InnerServiceSMO;
import com.java110.intf.system.IFileInnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.po.chainInoutOrder.ChainProductPo;
import com.java110.po.chainInoutOrder.ChainProductDetailPo;
import com.java110.po.chainInoutOrder.ChainProductValuePo;
import com.java110.po.file.FileRelPo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 类表述：更新
 * 服务编码：chainProduct.updateChainProduct
 * 请求路劲：/app/chainProduct.UpdateChainProduct
 * add by 吴学文 at 2022-06-20 16:20:53 mail: 928255095@qq.com
 * open source address: https://gitee.com/wuxw7/MicroCommunity
 * 官网：http://www.homecommunity.cn
 * 温馨提示：如果您对此文件进行修改 请不要删除原有作者及注释信息，请补充您的 修改的原因以及联系邮箱如下
 * // modify by 张三 at 2021-09-12 第10行在某种场景下存在某种bug 需要修复，注释10至20行 加入 20行至30行
 */
@Java110Cmd(serviceCode = "chainProduct.updateChainProduct")
public class UpdateChainProductCmd extends Cmd {

    private static Logger logger = LoggerFactory.getLogger(UpdateChainProductCmd.class);

    @Autowired
    private IFileInnerServiceSMO fileInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IChainProductV1InnerServiceSMO chainProductV1InnerServiceSMOImpl;

    @Autowired
    private IChainProductValueV1InnerServiceSMO chainProductValueV1InnerServiceSMOImpl;

    @Autowired
    private IChainProductDetailV1InnerServiceSMO chainProductDetailV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        Assert.hasKeyAndValue(reqJson, "productId", "productId不能为空");
        Assert.hasKeyAndValue(reqJson, "csId", "请求报文中未包含csId");
        Assert.hasKeyAndValue(reqJson, "catalogId", "请求报文中未包含catalogId");
        Assert.hasKeyAndValue(reqJson, "prodName", "请求报文中未包含prodName");
        Assert.hasKey(reqJson, "carouselFigurePhotos", "请求报文中未包含轮播图");
        Assert.hasKey(reqJson, "productSpecs", "请求报文中未包含规格信息");
    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        ChainProductPo chainProductPo = BeanConvertUtil.covertBean(reqJson, ChainProductPo.class);
        int flag = chainProductV1InnerServiceSMOImpl.updateChainProduct(chainProductPo);
        if (flag < 1) {
            throw new CmdException("更新数据失败");
        }
        //删除原有封面图片信息
        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(chainProductPo.getProductId());
        fileRelPo.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_COVER);
        fileRelInnerServiceSMOImpl.deleteFileRel(fileRelPo);
        //删除原有轮播图片信息
        fileRelPo = new FileRelPo();
        fileRelPo.setObjId(chainProductPo.getProductId());
        fileRelPo.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        fileRelInnerServiceSMOImpl.deleteFileRel(fileRelPo);
        String coverPhoto = reqJson.getString("coverPhoto");
        JSONArray carouselFigurePhotos = reqJson.getJSONArray("carouselFigurePhotos");
        JSONArray productSpecs = reqJson.getJSONArray("productSpecs");
        doSavaFile(coverPhoto, chainProductPo, FileRelDto.REL_TYPE_CD_GOODS_COVER);
        for (int carouselIndex = 0; carouselIndex < carouselFigurePhotos.size(); carouselIndex++) {
            doSavaFile(carouselFigurePhotos.getString(carouselIndex), chainProductPo, FileRelDto.REL_TYPE_CD_GOODS_CAROUSEL_FIGURE);
        }
        ChainProductValuePo chainProductValuePo = null;
        chainProductValuePo.setCsId(chainProductPo.getCsId());
        chainProductValuePo.setProductId(chainProductPo.getProductId());
        flag = chainProductValueV1InnerServiceSMOImpl.deleteChainProductValue(chainProductValuePo);
        if (flag < 1) {
            throw new IllegalArgumentException("删除规格失败");
        }
        for (int specIndex = 0; specIndex < productSpecs.size();specIndex++) {
            chainProductValuePo = new ChainProductValuePo();
            chainProductValuePo = BeanConvertUtil.covertBean(productSpecs.getJSONObject(specIndex),ChainProductValuePo.class);
            chainProductValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId  ));
            chainProductValuePo.setProductId(chainProductPo.getProductId());
            chainProductValuePo.setCsId(chainProductPo.getCsId());

            flag = chainProductValueV1InnerServiceSMOImpl.saveChainProductValue(chainProductValuePo);
            if (flag < 1) {
                throw new IllegalArgumentException("保存规格失败");
            }
        }
        ChainProductDetailPo chainProductDetailPo = new ChainProductDetailPo();
        chainProductDetailPo.setCsId(chainProductPo.getCsId());
        chainProductDetailPo.setProductId(chainProductPo.getProductId());
        flag = chainProductDetailV1InnerServiceSMOImpl.deleteChainProductDetail(chainProductDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存商品详细信息失败");
        }
        chainProductDetailPo = new ChainProductDetailPo();
        chainProductDetailPo.setContent(reqJson.getString("content"));
        chainProductDetailPo.setCsId(chainProductPo.getCsId());
        chainProductDetailPo.setProductId(chainProductPo.getProductId());
        chainProductDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
        flag = chainProductDetailV1InnerServiceSMOImpl.saveChainProductDetail(chainProductDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("保存描述失败");
        }
        cmdDataFlowContext.setResponseEntity(ResultVo.success());
    }

    /**
     *  供应链商品
     *
     * @param photo
     * @param chainProductPo
     */
    private void doSavaFile(String photo, ChainProductPo chainProductPo, String fileTypeCd) {

        FileDto fileDto = new FileDto();
        fileDto.setCommunityId("-1");
        fileDto.setContext(photo);
        fileDto.setFileId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_file_id));
        fileDto.setFileName(fileDto.getFileId());

        fileDto.setSuffix("jpeg");
        String fileName = fileInnerServiceSMOImpl.saveFile(fileDto);

        FileRelPo fileRelPo = new FileRelPo();
        fileRelPo.setObjId(chainProductPo.getProductId());
        fileRelPo.setRelTypeCd(fileTypeCd);
        fileRelPo.setFileRelId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_relId));
        fileRelPo.setFileRealName(fileName);
        fileRelPo.setFileSaveName(fileName);
        fileRelPo.setSaveWay(FileRelDto.SAVE_WAY_FTP);
        int save = fileRelInnerServiceSMOImpl.saveFileRel(fileRelPo);

        if (save < 1) {
            throw new IllegalArgumentException("保存文件失败");
        }
    }
}
